package com.sfj.system.controller;

import com.kaka.starter.control.dto.ResultBean;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sfj.system.dto.task.TaskQueryDTO;
import com.sfj.system.dto.task.TaskQueryReportDTO;
import com.sfj.system.dto.task.TaskReportDTO;
import com.sfj.system.service.task.TaskQueryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author kaka
 * @Date 2025/07/01
 */
@RestController
@RequestMapping("task")
@Api(tags = "督办任务查询")
@Slf4j
public class TaskQueryController {

    @Autowired
    private TaskQueryService taskQueryService;

    @GetMapping("/statistics")
    @ApiOperation(value = "首页数据统计", notes = "首页数据统计")
    public ResultBean getTaskStatistics() {
        return ResultBean.succeed(taskQueryService.getTaskStatistics());
    }

    @PostMapping("/query")
    @ApiOperation(value = "获取所有督办任务", notes = "获取所有督办任务列表")
    public ResultBean query(@RequestBody TaskQueryDTO taskQueryDTO) {
        return ResultBean.succeed(taskQueryService.queryTaskListByPage(taskQueryDTO));
    }

    @PostMapping("/data")
    @ApiOperation(value = "督察任务数据接口", notes = "督察任务数据接口")
    public ResultBean data(@Valid @RequestBody TaskQueryReportDTO taskQueryDTO){
        List<TaskReportDTO> data = taskQueryService.getData(taskQueryDTO);
        return ResultBean.succeed(data);
    }
    @PostMapping("/report")
    @ApiOperation(value = "督察任务数据报表", notes = "督察任务数据报表")
    public void report(HttpServletResponse response, @Valid @RequestBody TaskQueryReportDTO taskQueryDTO){
        if (taskQueryDTO.getRfStartDate() == null || taskQueryDTO.getRfEndDate() == null) {
            //return ResultBean.fail("统计必须选择日期");
        }

        try {
            // 1. 查询数据，替换成你自己的服务调用
            List<TaskReportDTO> data = taskQueryService.getReport(taskQueryDTO);
            // 2. 创建xls工作簿
            Workbook workbook = new HSSFWorkbook();
            Sheet sheet = workbook.createSheet("督察任务表");

            // 3. 创建表头
            Row header = sheet.createRow(0);
            header.createCell(0).setCellValue("整改单位");
            header.createCell(1).setCellValue("问题类型");
            header.createCell(2).setCellValue("总任务");
            header.createCell(3).setCellValue("已完成任务");
            header.createCell(4).setCellValue("未完成任务");
            header.createCell(5).setCellValue("超时任务");

            // 4. 填充数据
            for (int i = 0; i < data.size(); i++) {
                TaskReportDTO row = data.get(i);
                Row sheetRow = sheet.createRow(i + 1);
                sheetRow.createCell(0).setCellValue(row.getGroupName());
                sheetRow.createCell(1).setCellValue(row.getProblemType());
                sheetRow.createCell(2).setCellValue(row.getTotal());
                sheetRow.createCell(3).setCellValue(row.getCompleteds());
                sheetRow.createCell(4).setCellValue(row.getNoCompleteds());
                sheetRow.createCell(5).setCellValue(row.getOverdues());
            }
            //自动调整列宽
            for (int col = 0; col <= 4; col++) {
                sheet.autoSizeColumn(col);
            }
            // 5. 设置响应头
            String fileName = "督察任务表表";
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

            // 6. 写出文件流
            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (Exception e) {
            response.setContentType("application/json;charset=UTF-8");
            try {
                log.error(e.getMessage());
                ResultBean<?> error = ResultBean.fail("导出失败：" + e.getMessage());
                response.getWriter().write(new ObjectMapper().writeValueAsString(error));
            } catch (IOException ioException) {
                // 最坏情况只能打日志
                ioException.printStackTrace();
            }
        }

    }

    @GetMapping("/get/{taskId}")
    @ApiOperation(value = "获取督办任务详情", notes = "根据ID获取督办任务详情")
    public ResultBean getById(@PathVariable Integer taskId) {
        return ResultBean.succeed(taskQueryService.getTaskById(taskId));
    }

    @GetMapping("/getTaskAndProblemById/{taskId}")
    @ApiOperation(value = "获取督办任务详情(包含反馈信息)", notes = "根据ID获取督办任务详情(包含反馈信息)")
    public ResultBean getTaskAndProblemById(@PathVariable Integer taskId) {
        return ResultBean.succeed(taskQueryService.getTaskAndProblemById(taskId));
    }


    @GetMapping("/getStatus/{taskId}")
    @ApiOperation(value = "获取task完整状态", notes = "获取task完整状态")
    public ResultBean getStatus(@PathVariable Integer taskId) {
        return ResultBean.succeed(taskQueryService.queryTaskStatus(taskId));
    }
}
